//5.controller
package com.wsz.security_fx.controller;

import com.google.code.kaptcha.Producer;
import com.wsz.security_fx.utils.RedisOperator;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;


@RequiredArgsConstructor
@RestController
public class VerifyCodeController {

    private final Producer producer;
    private final RedisOperator redisOperator;

    @GetMapping("/vc.jpg")
    public String getVC(HttpSession session) throws IOException {
        String text = redisOperator.get("code");
        if(StringUtils.isEmpty(text))
        {
            //1.生成验证码
            text = producer.createText();
            //2.放入session redis
            redisOperator.set("code",text,5 * 60);
        }
        //3.生成图片
        BufferedImage image = producer.createImage(text);
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(image,"jpg",fos);
        //4.返回base64
        return Base64.encodeBase64String(fos.toByteArray());
    }
}
